// 玩家管理页面

import { PlayerAppServiceFactory, IPlayerAppService } from '../application/PlayerAppService';
import { DateUtils } from '../infrastructure/utils/DateUtils';
import { AppError } from '../infrastructure/error/AppError';
import { Flex, FlexDirection, ItemAlign, FlexAlign, Text, View, Input, Button, Scroll, Progress, ProgressType } from '@kit.ArkUI';

@Entry
@Component
struct PlayerManagement {
  // 状态管理
  private playerService: IPlayerAppService = PlayerAppServiceFactory.createService();
  private players: any[] = [];
  private newPlayerName: string = '';
  private selectedPlayer: any = null;
  private showPlayerDetails: boolean = false;
  private loading: boolean = false;
  private errorMessage: string = '';
  private successMessage: string = '';

  // 页面加载时获取玩家列表
  aboutToAppear() {
    this.loadPlayers();
  }

  // 加载所有玩家
  async loadPlayers() {
    this.loading = true;
    this.clearMessages();
    
    try {
      const playersData = await this.playerService.getAllPlayers();
      this.players = playersData;
    } catch (error) {
      this.handleError('加载玩家列表失败', error);
    } finally {
      this.loading = false;
    }
  }

  // 创建新玩家
  async createNewPlayer() {
    if (!this.newPlayerName.trim()) {
      this.errorMessage = '请输入玩家名称';
      return;
    }

    this.loading = true;
    this.clearMessages();
    
    try {
      await this.playerService.createPlayer(this.newPlayerName);
      this.successMessage = `玩家 "${this.newPlayerName}" 创建成功！`;
      this.newPlayerName = ''; // 清空输入框
      this.loadPlayers(); // 重新加载玩家列表
    } catch (error) {
      this.handleError('创建玩家失败', error);
    } finally {
      this.loading = false;
    }
  }

  // 查看玩家详情
  async viewPlayerDetails(playerId: number) {
    this.loading = true;
    this.clearMessages();
    
    try {
      this.selectedPlayer = await this.playerService.getPlayerDetails(playerId);
      this.showPlayerDetails = true;
    } catch (error) {
      this.handleError('获取玩家详情失败', error);
    } finally {
      this.loading = false;
    }
  }

  // 关闭玩家详情
  closePlayerDetails() {
    this.showPlayerDetails = false;
    this.selectedPlayer = null;
  }

  // 处理错误
  handleError(message: string, error: any) {
    if (error instanceof AppError) {
      this.errorMessage = `${message}: ${error.message}`;
    } else {
      this.errorMessage = message;
    }
    console.error(error);
  }

  // 清空消息
  clearMessages() {
    this.errorMessage = '';
    this.successMessage = '';
  }

  // 获取技能名称
  getSkillName(type: string): string {
    const skillNames: Record<string, string> = {
      observation: '观察力',
      deduction: '推理能力',
      analysis: '分析能力',
      intuition: '直觉'
    };
    return skillNames[type] || type;
  }

  // 获取技能等级名称
  getSkillLevelName(level: string): string {
    const levelNames: Record<string, string> = {
      beginner: '入门',
      intermediate: '熟练',
      advanced: '精通',
      expert: '专家'
    };
    return levelNames[level] || level;
  }

  // 构建玩家列表项
  buildPlayerItem(player: any) {
    return (
      <Flex className="player-item" onClick={() => this.viewPlayerDetails(player.id)}>
        <View className="player-avatar">
          <Text>{player.name.charAt(0)}</Text>
        </View>
        <Flex className="player-info" direction={FlexDirection.Column}>
          <Text className="player-name">{player.name}</Text>
          <Text className="player-meta">等级: {player.level} | {player.rank} | 案件: {player.stats.casesSolved}  solved</Text>
        </Flex>
        <Text className="player-accuracy">准确率: {player.stats.accuracyRate.toFixed(1)}%</Text>
      </Flex>
    );
  }

  // 构建玩家详情视图
  buildPlayerDetails() {
    if (!this.selectedPlayer) return null;
    
    return (
      <Flex className="player-details-overlay" onClick={this.closePlayerDetails}>
        <Flex className="player-details-content" onClick={(e) => e.stopPropagation()} direction={FlexDirection.Column}>
          <Flex className="details-header" justifyContent={FlexAlign.SpaceBetween}>
            <Text className="details-title">玩家详情</Text>
            <Button className="close-btn" onClick={this.closePlayerDetails}>×</Button>
          </Flex>
          
          <Scroll className="details-body">
            <Flex className="player-profile" direction={FlexDirection.Column} alignItems={ItemAlign.Center}>
              <View className="profile-avatar">
                <Text>{this.selectedPlayer.name.charAt(0)}</Text>
              </View>
              <Text className="profile-name">{this.selectedPlayer.name}</Text>
              <Text className="profile-rank">{this.selectedPlayer.rank}</Text>
              <Text className="profile-level">等级 {this.selectedPlayer.level}</Text>
            </Flex>
            
            <View className="section">
              <Text className="section-title">统计信息</Text>
              <Flex className="stats-grid">
                <View className="stat-item">
                  <Text className="stat-value">{this.selectedPlayer.stats.casesSolved}</Text>
                  <Text className="stat-label">解决案件</Text>
                </View>
                <View className="stat-item">
                  <Text className="stat-value">{this.selectedPlayer.stats.casesFailed}</Text>
                  <Text className="stat-label">失败案件</Text>
                </View>
                <View className="stat-item">
                  <Text className="stat-value">{this.selectedPlayer.stats.accuracyRate.toFixed(1)}%</Text>
                  <Text className="stat-label">准确率</Text>
                </View>
                <View className="stat-item">
                  <Text className="stat-value">{DateUtils.formatDuration(this.selectedPlayer.stats.totalPlayTime)}</Text>
                  <Text className="stat-label">总游戏时间</Text>
                </View>
              </Flex>
            </View>
            
            <View className="section">
              <Text className="section-title">技能</Text>
              {this.selectedPlayer.skills.map((skill: any) => (
                <View key={skill.type} className="skill-item">
                  <Text className="skill-name">{this.getSkillName(skill.type)}</Text>
                  <Text className="skill-level">{this.getSkillLevelName(skill.level)}</Text>
                  <Progress
                    percent={(skill.experience / skill.maxExperience) * 100}
                    type={ProgressType.Linear}
                    strokeWidth={8}
                  />
                  <Text className="skill-exp">{skill.experience}/{skill.maxExperience}</Text>
                </View>
              ))}
            </View>
            
            <View className="section">
              <Text className="section-title">成就 ({this.selectedPlayer.achievements.length})</Text>
              {this.selectedPlayer.achievements.length > 0 ? (
                this.selectedPlayer.achievements.map((achievement: any) => (
                  <View key={achievement.id} className="achievement-item">
                    <Text className="achievement-name">{achievement.name}</Text>
                    <Text className="achievement-desc">{achievement.description}</Text>
                    <Text className="achievement-date">解锁时间: {DateUtils.formatDateTime(achievement.unlockedAt)}</Text>
                  </View>
                ))
              ) : (
                <Text className="no-data">暂无成就</Text>
              )}
            </View>
          </Scroll>
        </Flex>
      </Flex>
    );
  }

  // 构建页面UI
  build() {
    Flex({
      direction: FlexDirection.Column,
      alignItems: ItemAlign.Stretch
    }) {
      // 页面标题
      Text('玩家管理')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 20, bottom: 20, horizontal: 20 })
        .textAlign(TextAlign.Center);

      // 创建玩家区域
      Flex({
        direction: FlexDirection.Column,
        alignItems: ItemAlign.Stretch,
        margin: { horizontal: 20, bottom: 20 }
      }) {
        Text('创建新玩家')
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
          .marginBottom(10);
        
        Flex({
          alignItems: ItemAlign.Center
        }) {
          Input({
            value: this.newPlayerName,
            placeholder: '输入玩家名称',
            onChange: (value: string) => this.newPlayerName = value
          })
            .width('70%')
            .height(40)
            .backgroundColor('#F5F5F5')
            .borderRadius(20)
            .padding({ horizontal: 20 });
          
          Button('创建')
            .marginLeft(10)
            .height(40)
            .borderRadius(20)
            .onClick(() => this.createNewPlayer());
        }
      }

      // 消息显示区域
      if (this.errorMessage) {
        Text(this.errorMessage)
          .fontColor('#ff4d4f')
          .margin({ horizontal: 20, bottom: 10 });
      }
      
      if (this.successMessage) {
        Text(this.successMessage)
          .fontColor('#52c41a')
          .margin({ horizontal: 20, bottom: 10 });
      }

      // 玩家列表
      Scroll() {
        if (this.loading) {
          // 加载状态
          Flex({
            justifyContent: FlexAlign.Center,
            alignItems: ItemAlign.Center,
            height: 300
          }) {
            Text('加载中...')
              .fontSize(16);
          }
        } else if (this.players.length === 0) {
          // 无数据状态
          Flex({
            justifyContent: FlexAlign.Center,
            alignItems: ItemAlign.Center,
            height: 300
          }) {
            Text('暂无玩家数据')
              .fontSize(16)
              .color('#86909C');
          }
        } else {
          // 玩家列表
          this.players.map(player => this.buildPlayerItem(player));
        }
      }
      .height('60%')
      .margin({ horizontal: 20 })
      .backgroundColor('#FFFFFF')
      .borderRadius(8)
      .border('1px solid #EEEEEE');

      // 玩家详情弹窗
      if (this.showPlayerDetails) {
        this.buildPlayerDetails();
      }
    }
    .height('100%')
    .backgroundColor('#F8F8F8');
  }
}